<?php
/**
 * Created by PhpStorm.
 * User: 13790
 * Date: 2018/3/16
 * Time: 16:04
 */

namespace app\admin\controller;


use think\Controller;
use Think\Exception;
use Think\Model;


class Admin extends Base
{
    public function lst(){
        $data = Model('admin')->sel();
//        $num =  Db::name('admin')->count();

        return  view('',['data'=>$data]);
    }
    public function add(){
        if(request()->isPost()){
            try{
                $res = model('Admin')->addData();
                if($res !== true){
                    throw new \Exception($res);
                }
            }catch (\Exception $e){
                $this->error($e->getMessage());
            }
            $this->success('添加成功','lst');
        }
        //将所有的角色都查询出来
        $role_data = db('role')->select();
        return view('',['role_data'=>$role_data]);
    }

    public function edit(){

            if (request()->isPost()) {
                try {
                    $res = model('Admin')->editData();
                    //当更新没有成功但是没有抛异常，咱把更新失败这几个字抛出
                    if ($res !== true) {
                       Exception($res);
                    }
                } catch (\Exception $e) {
                    $this->error($e->getMessage());
                }

                $this->success('更新成功');
            }
        $id = input('param.id');
        $data = model('Admin')
            ->alias('a')
            ->field('a.*, group_concat(b.role_id) role_ids')
            ->join('admin_role b','a.id = b.admin_id','LEFT')
            ->find($id);

        //查询所有的角色信息
        $role_data = db('Role')->select();
        return view('',['data'=>$data,'role_data'=>$role_data]);

    }

    public function del($id){
        $m = db('Admin');
        $num_rows = $m->where("id={$id}")->delete();
        if($num_rows>0){
            $url = U('Index/fun');
            $this->success('删除成功！',"{$url}");
        }else{
            $this->error('删除失败！');
        }
    }
}